// This is unpublished source code. Michah Lerner 2006

package trieMatch.util.coll;

import java.util.Comparator;

/**
 * Typesafe pairs which implements a comparator over pairs. Also works when the component types are collections of
 * comparable objects, using the natural iteration order of the collections.
 * 
 * @author Michah.Lerner
 * 
 * @param <S>
 *            type "car" "head" or "s" of the pair
 * @param <T>
 *            type "cdr" "tail" or "t" of the pair
 */
public class Pair<S extends Comparable, T extends Comparable> implements Comparator<Pair<S, T>>, Comparable<Pair<S, T>> {
	S s;
	T t;

	@SuppressWarnings("unchecked")
	public Pair() {
		s = (S) ("");
		t = (T) (Integer.valueOf(-1));
	}

	public Pair(final S s, final T t) {
		this.s = s;
		this.t = t;
	}

	public S S() {
		return s;
	}

	public S s() {
		return s;
	}

	public T T() {
		return t;
	}

	public T t() {
		return t;
	}

	public Pair<S, T> set(final S s, final T t) {
		this.s = s;
		this.t = t;
		return this;
	}

	public S setS(final S s) {
		this.s = s;
		return s;
	}

	public T setT(final T t) {
		this.t = t;
		return t;
	}

	@Override
	public String toString() {
		return "{" + s().toString() + ", " + t().toString() + "}";
	}

	// the Comparator
	@SuppressWarnings( { "unchecked" })
	public int compare(final Pair<S, T> o1, final Pair<S, T> o2) {
		int cmp = (o1.s).compareTo(o2.s);
		if (cmp == 0) {
			cmp = o1.t.compareTo(o2.t);
		}
		return cmp;
	}

	// the Compararable
	public int compareTo(final Pair<S, T> o) {
		return (compare(this, o));
	}
}
